﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace YahooMoviesStormer
{
    public partial class Main : Form
    {
        BackgroundWorker worker = new BackgroundWorker();
        System.Windows.Forms.Timer timerUpdate = new System.Windows.Forms.Timer();
        List<string> logLines = new List<string>();
        WorkerData workerData = new WorkerData();

        enum ButtonMainStates
        {
            Start,
            Stop
        }

        public class WorkerData
        {
            public string[] Binds { get; set; }
            public string ReviewURL { get; set; }
            public bool DownVote { get; set; }
        }

        public Main()
        {
            InitializeComponent();
            LoadConfig();

            worker.DoWork += worker_DoWork;
            worker.RunWorkerCompleted += worker_RunWorkerCompleted;
            worker.WorkerSupportsCancellation = true;

            timerUpdate.Tick += timerUpdate_Tick;
            timerUpdate.Interval = 300;
            timerUpdate.Start();
        }

        void LoadConfig()
        {
            Storage.Load();
            richTextBoxBinds.Text = string.Join(Environment.NewLine, Storage.Accounts);
            textBoxReviewURL.Text = Storage.ReviewURL;
        }

        void SaveConfig()
        {
            Storage.Accounts = new List<string>(richTextBoxBinds.Lines);
            Storage.ReviewURL = textBoxReviewURL.Text;
            Storage.Save();
        }

        void timerUpdate_Tick(object sender, EventArgs e)
        {


            var logLinesArray = logLines.ToArray();
            var lastLineNew = logLinesArray.Length > 0 ? logLinesArray[logLinesArray.Length - 1]: "";
            var lastLineActual = richTextBoxLog.Lines.Length > 0 ? richTextBoxLog.Lines[richTextBoxLog.Lines.Length - 1] : "";
            if (string.IsNullOrWhiteSpace(richTextBoxLog.Text) || lastLineNew != lastLineActual)
            {
                richTextBoxLog.Text = string.Join(Environment.NewLine, logLinesArray);
                richTextBoxLog.SelectionStart = richTextBoxLog.TextLength;
                richTextBoxLog.ScrollToCaret();
            }

        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            foreach (string bind in workerData.Binds)
            {
                if (worker.CancellationPending) return;

                var bindParts = bind.Split(':');
                var Proxy = bindParts.Length < 5 ? (bindParts.Length == 2 ? null : new Communications.ProxyInfo { IP = bindParts[2], Port = bindParts[3] }) : new Communications.ProxyInfo { IP = bindParts[2], Port = bindParts[3], User = bindParts[4], Password = bindParts[5] };

                var voteInfo = new YahooClient.VoteInformation { ReviewURL = workerData.ReviewURL, Username = bindParts[0], Password = bindParts[1], Proxy = Proxy, DownVote = workerData.DownVote };
                YahooClient client = new YahooClient();
                client.LoginPerformed += client_LoginPerformed;
                client.VotePerformed += client_VotePerformed;
                client.AlreadVoted += client_AlreadVoted;
                client.PerformVote(voteInfo, false);
                Thread.Sleep(350);
            }
        }

        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            buttonMain.Text = ButtonMainStates.Start.ToString();
        }

        void client_AlreadVoted(YahooClient client)
        {
            PerformLog("Already voted with " + client.voteInformation.Username);
        }

        void client_LoginPerformed(YahooClient client, bool successful)
        {
            if (successful)
                PerformLog("Logged in with " + client.voteInformation.Username);
            else
                PerformLog("Failed to login with " + client.voteInformation.Username);
        }

        void client_VotePerformed(YahooClient client, bool successful)
        {
            if (successful)
                PerformLog("Voted with " + client.voteInformation.Username);
            else
                PerformLog("Failed to vote with " + client.voteInformation.Username);
        }

        private void buttonMain_Click(object sender, EventArgs e)
        {
            if (buttonMain.Text == ButtonMainStates.Start.ToString())
            {
                buttonMain.Text = ButtonMainStates.Stop.ToString();
                workerData.Binds = richTextBoxBinds.Lines;
                workerData.ReviewURL = textBoxReviewURL.Text;
                workerData.DownVote = checkBoxVote.Checked;
                worker.RunWorkerAsync();
            }
            else
            {
                buttonMain.Text = ButtonMainStates.Start.ToString();
                worker.CancelAsync();
                buttonMain.Enabled = false;
            }
        }

        void PerformLog(string update)
        {
            logLines.Add(DateTime.Now.ToLongTimeString() + " - " + update);
            if (logLines.Count > 100) logLines.RemoveAt(0);
        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            SaveConfig();
        }
    }
}
